﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Text;

public class TextureImportSetting : AssetPostprocessor
{
    /// <summary>
    /// 图片导入之前调用，可设置图片的格式、Tag……
    /// </summary>
    void OnPreprocessTexture()
    {
        TextureImporter importer = (TextureImporter)assetImporter;

        string path = importer.assetPath;

        if (importer.assetPath.Contains("media2d"))
        {
            importer.npotScale = TextureImporterNPOTScale.None;
            importer.textureType = TextureImporterType.Advanced;
            importer.isReadable = true;
            //importer.textureType = TextureImporterType.Sprite; // 设置为Sprite类型
            importer.spriteImportMode = SpriteImportMode.Single;
            importer.mipmapEnabled = true; // 禁用mipmap
            importer.spritePackingTag = ""; // 设置Sprite的打包Tag
            importer.textureFormat = TextureImporterFormat.AutomaticTruecolor;
            importer.filterMode = FilterMode.Bilinear;
            importer.spritePixelsPerUnit = 1;

            TextureImporterSettings texSettings = new TextureImporterSettings();
            importer.ReadTextureSettings(texSettings);
            texSettings.spriteAlignment = (int)SpriteAlignment.BottomLeft;
            importer.SetTextureSettings(texSettings);

            Debug.Log("OnPreprocessTexture");

            CreateProperty(importer);

        }
    }

    void CreateProperty(TextureImporter importer)
    {
        string cfgPath = Path.GetDirectoryName(importer.assetPath) + "/" + Path.GetFileNameWithoutExtension(importer.assetPath) + ".bytes";

        Debug.Log(cfgPath);

        if (AssetDatabase.LoadAssetAtPath<Object>(cfgPath) != null)
            return;

        string path = Path.GetFullPath(cfgPath);

        Debug.Log(path);

        FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write);
        //  是否可以拖拽.
        BinaryWriter writer = new BinaryWriter(fs, Encoding.UTF32);
        writer.Write('1');
        writer.Close();

        AssetDatabase.Refresh();
    }
}
